<?php


	namespace app\services;


	use app\lib\exception\ToastException;
	use app\model\Member;
	use think\facade\Cache;

	class WxSystemServices
	{

		const LOGIN_TOKEN = 'login_token';
		const EXPIRETIME  = 60 * 60 * 2;

		public function login ($request) {
			$code = $request->get("code");
			//加入管理端来管理
			$loginUrl = sprintf(config('wx.loginUrl'), config('wx.appid'), config('wx.secret'), $code);
			$ret = json_decode(file_get_contents($loginUrl), true);

			if (array_key_exists('errcode', $ret)) {
				throw new ToastException($ret['errmsg'], $ret['errcode']);
			}

			$openid = $ret['openid'];
			$session_key = $ret['session_key'];

			//检测用户
			$member = Member::where('openid', '=', $openid)->find();
			if ($member) {//用户存在,检测是否授权过
				$token = Cache::get(self::LOGIN_TOKEN . '_' . $member->id);
				//未授权或者授权信息失效
				if (!$token) {
					$token = md5(self::LOGIN_TOKEN . '_' . $member->id);
					Cache::set($token, $member->id, self::EXPIRETIME);
				}
			} else {
				$res = Member::create(['openid' => $openid,'createtime'=>time()]);
				$token = md5(self::LOGIN_TOKEN . '_' . $res->id);
				Cache::set($token, $res->id, self::EXPIRETIME);
			}

			return compact('token', 'session_key');
		}

		public function getUserInfo ($request) {
			$iv = $request->post('iv');
			$encryptedData = $request->post('encryptedData');
			$sessionKey = $request->post('session_key');

			require root_path() . 'extend/wxCrypt/wxBizDataCrypt.php';

			$wxBizDataCrypt = new \WXBizDataCrypt(config('wx.appid'), $sessionKey);
			$errCode = $wxBizDataCrypt->decryptData($encryptedData, $iv, $data);
			if ($errCode != 0) {
				throw new ToastException('解密失败');
			}
			$ret = json_decode($data, true);


			return $ret;
		}
	}




